<?php

namespace App\Http\Controllers\Cart;

use App\Models\Address;
use App\Models\Attr;
use App\Models\Cart;
use App\Models\Goods;
use App\Models\Huopin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CartController extends Controller
{
    public function addCart($goods_id,$huopin_id,$num){
        // 查询当前货品在购物车中的数据
        $cart=Cart::where('user_id',auth()->id())->where('huopin_id',$huopin_id)->first();
        if($cart){
            // 存在则更新货品数量
            $cart->update(['num'=>$cart['num']+$num]);
        }else{
            // 否则新建货品数据
            Cart::create([
                'goods_id'=>$goods_id,
                'huopin_id'=>$huopin_id,
                'user_id'=>auth()->id(),
                'num'=>$num
            ]);
        }

        // 返回界面
        return redirect()->route('cart.show',compact('goods_id','huopin_id','num'));
    }

    public function show($goods_id,$huopin_id,$num){
        $goods=Goods::where('id',$goods_id)->first();
        $huopin=Huopin::where('id',$huopin_id)->first();
        $attrs=[];
        foreach ($huopin['attrs'] as $v){
            $attrs[]=Attr::where('id',$v)->value('attr_name');
        }
//        dd($attrs);
        return view('cart.addCart',compact('goods','num','attrs'));
    }

    public function cartList(){

        $newcarts=Cart::where('user_id',auth()->id())->with('goods','huopin')->get();

//        dd($carts->toArray());
        return view('cart.cartList',compact('newcarts'));
    }

    // 改变商品数量
    public function changeNum($type,Cart $cart){
        // 获取当前货品数据
        $huopin=$cart->huopin;
        if($type=='plus'){
            if($cart['num']>=$huopin['kucun']){
                return ['valid'=>0,'message'=>'已达到该货品库存上限'];
            }
            // 将购物车数量加1
            $cart->update(['num'=>$cart['num']+1]);
        }else{
            if($cart['num']==1){
                return ['valid'=>0,'message'=>'数量不能少于1'];
            }
            // 将购物车数量减1
            $cart->update(['num'=>$cart['num']-1]);
        }
        return ['valid'=>1,'message'=>'操作成功'];
    }

    // 删除当前选中商品
    public function deleteCart(Cart $cart){
        $cart->delete();

        return ['valid'=>1,'message'=>'删除成功'];
    }

    // 批量删除商品
    public function deleteMany($ids){
        $arr=explode(',',$ids);
        foreach ($arr as $v){
            Cart::destroy($v);
        }
        return back()->with('success','删除成功');
    }

    //  结算方法
    public function jiesuan($ids ,$total){
        $arr=explode(',',$ids);

        $carts=Cart::whereIn('id',$arr)->get();

        $addresses=Address::where('user_id',auth()->id())->orderBy('created_at','desc')->get();

        $defaultAddress=Address::where('is_default',1)->where('user_id',auth()->id())->first();


        return view('cart.jiesuan',compact('total','carts','addresses','defaultAddress','ids'));
    }
}
